package com.example.controller.course;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.example.enums.Status;
import com.example.pojo.Course;
import com.example.pojo.CourseRecord;
import com.example.pojo.ElementSelect;
import com.example.pojo.ElementTree;
import com.example.service.course.CourseService;
import com.example.service.course.CourseclassServce;
import com.example.tools.ImageUilt;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

//@CrossOrigin
@Slf4j
@Controller
@RequestMapping("/Course")
public class CourseController {
    private static final List<MultipartFile> files = new ArrayList<>();
    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com/";
    //访问路径
    private static final String ENDPOINT1 = "https://jinsi--siyun.oss-cn-beijing.aliyuncs.com/";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static final String ACCESSKEYID = "LTAI5tRRxLCt6E7gzG5pxxSG";
    private static final String ACCESSKEYSERET = "953LSP6kXGnTeyDyGoJK4LOU0kcigZ";
    // 填写Bucket名称，例如examplebucket。
    private static final String BUCKETNAME = "jinsi--siyun";
    @Autowired
    private CourseclassServce courseclassServce;
    @Autowired
    private CourseService courseService;

    /**
     * 功能描述: <获取课程菜单树>
     * 〈〉
     * @Param: []
     * @Return: java.util.List<com.example.pojo.ElementTree>
     * @Author: song
     * @Date: 2022/11/14 15:36
     */
    @ResponseBody
    @RequestMapping("/getTree")
    public List<ElementTree> getTree(){
        List<ElementTree> treeData = courseclassServce.getTreeData();
        return treeData;
    }
    /**
     * 功能描述: <点击树获取数据和模糊查获取数据>
     * 〈〉
     * @Param: [course]
     * @Return: java.util.List<com.example.pojo.Course>
     * @Author: song
     * @Date: 2022/11/14 15:41
     */
    @ResponseBody
    @RequestMapping("/getTable")
    public List<Course> getTable(Course course){
        List<Course> table = courseService.getTable(course);
        log.info("根据分类获取了一次表格数据");
        System.out.println(table);
        return table;
    }



   /**
    * 功能描述: <点击更新按钮更细课程上下架>
    * 〈〉
    * @Param: [id, status]
    * @Return: java.util.Map<java.lang.String,java.lang.String>
    * @Author: song
    * @Date: 2022/11/11 9:03
    */
    @ResponseBody
    @RequestMapping("/UpdateStatus")
    public int UpdateStatus(Integer id,Integer status){
        Status status1 = courseService.UpdateStatus(id, status);
        log.info("编辑了一个id为 {} 的课程的状态",id);
        return status1.getCODE();
    }

    /**
     * 功能描述: <删除指定课程>
     * 〈〉
     * @Param: [id]
     * @Return: boolean
     * @Author: song
     * @Date: 2022/11/11 9:05
     */
    @ResponseBody
    @RequestMapping("/deleteCourse")
    public boolean deleteCourse(Integer id){
        System.out.println(id);
        boolean b = courseService.deleteCourse(id);
        log.info("删除了了一个id为 {} 的课程的状态",id);
        return b;
    }
    /**
     * 功能描述: <获取课程审核详情>
     * 〈〉
     * @Param: [courseId]
     * @Return: java.util.List<com.example.pojo.CourseRecord>
     * @Author: song
     * @Date: 2022/11/11 10:05
     */
    @ResponseBody
    @RequestMapping("/cStatus")
    public List<CourseRecord> cStatus(Integer courseId){
        List<CourseRecord> recordByCourseId = courseService.getRecordByCourseId(courseId);
        log.info("获取了一个id为 {} 的审核记录",courseId);
        return recordByCourseId;
    }
    /**
     * 功能描述: <编辑页面选择上传人时发送请求模糊查对应的>
     * 〈〉
     * @Param: [name]
     * @Return: java.util.List<com.example.pojo.ElementSelect>
     * @Author: song
     * @Date: 2022/11/12 10:39
     */
    @ResponseBody
    @RequestMapping("/getUser")
    public List<ElementSelect> getUser(String name){
        List<ElementSelect> user = courseService.getUser(name);
        log.info("获取了一次后台用户信息");
        return user;
    }
    /**
     * 功能描述: 裁剪图片大小
     * 〈〉
     * @Param: [file]
     * @Return: java.io.File
     * @Author: song
     * @Date: 2022/11/12 8:15
     */
    @ResponseBody
    @RequestMapping("/uploadImage")
    public File uploadImage(@RequestBody MultipartFile file){
        System.out.println(file.getOriginalFilename());
        File file1 = ImageUilt.cutOutImage(file, 0.5, "C:\\Users\\song\\Desktop\\"+file.getOriginalFilename());
//        try {
//            multipartFile.transferTo(file);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return file1;
    }
    @ResponseBody
    @RequestMapping("/addCourse")
    public boolean addCourse(@RequestBody Course course){
        course.setCourseCstatus(Status.DOWN.getCODE());
        Date date = new Date();
        course.setCreateDate(new Timestamp(date.getTime()));
        System.out.println(files);
        for (MultipartFile file : files) {

            String hz = file.getOriginalFilename().split("\\.")[1];
            System.out.println(hz);
            if (hz.equals("jpg")||hz.equals("jpeg") ||hz.equals("GIF")||hz.equals("png") ||!hz.equals("mp4")){
                course.setUrl(ENDPOINT1+"siyun/"+file.getOriginalFilename());
                System.out.println(course);
            }else if (hz.equals("mp4")){
                course.setCourseUrl(ENDPOINT1+"siyun/"+file.getOriginalFilename());
                System.out.println(course);
            }
        }
        course.setCourseNo(1);
        course.setUserId(1);
        course.setSaleNum(0);
        course.setCourseId(1);
        course.setCreateId(1);
        System.out.println(course);
        boolean b = courseService.addCourse(course);
        return b;
    }
    /**
     * 功能描述: <编辑课程>
     * 〈〉
     * @Param: [course]
     * @Return: boolean
     * @Author: song
     * @Date: 2022/11/13 11:01
     */
    @ResponseBody
    @RequestMapping("/updateCourse")
    public boolean updateCourse(@RequestBody Course course){
        boolean b = courseService.updateCourse(course);

        return b;
    }
    /**
     * 功能描述: <上传文件到服务器>
     * 〈〉
     * @Param: [file]
     * @Return: void
     * @Author: song
     * @Date: 2022/11/13 16:01
     */
    @ResponseBody
    @RequestMapping("/upload")
    public  String  aliyun(MultipartFile file) throws IOException {
            //上传的oos的文件名称
            String objectName = "siyun/"+file.getOriginalFilename();
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSERET);
            //创建文件流
            InputStream inputStream = file.getInputStream();
        try {
                //文件上传至oss服务器
                PutObjectResult putObjectResult = ossClient.putObject(BUCKETNAME, objectName, inputStream);
                files.add(file);
                //上传到服务器的路径
                log.info("文件在服务器的路径:{}",ENDPOINT+objectName);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();

            }
        }
        return ENDPOINT1+objectName;
    }
//    @ResponseBody
//    @RequestMapping("/uploadVideo")
//    public String Video(MultipartFile file){
//
//        String originalFilename = file.getOriginalFilename();
//        System.out.println(originalFilename);
//        files.add(file);
////        服务器路径
//        File newFile=null;
//        if (file.getOriginalFilename().split("\\.")[1].equals("mp4")){
//            newFile = new File(VideoLOCALPATH+file.getOriginalFilename());
//        }else if(file.getOriginalFilename().split("\\.")[1].equals("jpg")){
//            newFile = new File(ImgLOCALPATH+file.getOriginalFilename());
//        }
//        try {
//            file.transferTo(newFile);
////            视频压缩
////            FfmpegVideo.toCompressFile(file.toString(),"D:\\迅雷下载\\221110\\02.mp4");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        if (file.getOriginalFilename().split("\\.")[1].equals("jpg")){
//            return ImgPATH+originalFilename;
//        }else{
//            return VideoPATH+originalFilename;
//        }
//
//    }



}
